<template>
  <el-header
      style="display: flex; justify-content: space-between; align-items: center; padding: 0 20px; background: linear-gradient(135deg, #409eff, #67c2ef); color: #fff; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); border-bottom: 1px solid #dcdcdc;"
  >
    <div class="logo">
      <img src="@/assets/logo.webp" alt="Logo" style="height: 40px; border-radius: 4px;" />
    </div>
    <el-menu
        mode="horizontal"
        router
        style="background: transparent; border-bottom: none;"
    >
      <el-menu-item
          v-if="isAdmin"
          index="/admin/admin-home"          style="color: #fff; font-weight: 500; border-radius: 4px; transition: background 0.3s ease; margin-right: 20px;"
      >首页</el-menu-item>
      <el-menu-item
          v-else-if="isRecruiter"
          index="/employer/employer-home"          style="color: #fff; font-weight: 500; border-radius: 4px; transition: background 0.3s ease; margin-right: 20px;"
      >首页</el-menu-item>
      <el-menu-item
          v-else-if="isApplicant"
          index="/job-seeker/recommended-positions"          style="color: #fff; font-weight: 500; border-radius: 4px; transition: background 0.3s ease; margin-right: 20px;"
      >首页</el-menu-item>
      <el-menu-item
          v-else
          index="/"          style="color: #fff; font-weight: 500; border-radius: 4px; transition: background 0.3s ease; margin-right: 20px;"
      >首页</el-menu-item>
      <el-menu-item
          style="color: #fff; font-weight: 500; border-radius: 4px; transition: background 0.3s ease; margin-right: 20px;"
      >推荐</el-menu-item>
      <el-menu-item

          style="color: #fff; font-weight: 500; border-radius: 4px; transition: background 0.3s ease; margin-right: 20px;"
      ><el-button type="primary" @click="searchJobs">搜索</el-button>
      </el-menu-item>
      <el-menu-item

          style="color: #fff; font-weight: 500; border-radius: 4px; transition: background 0.3s ease; margin-right: 20px;"
      >公司</el-menu-item>
      <el-menu-item
          v-if="isRecruiter"
          index="/recruiter/jobs"
          style="color: #fff; font-weight: 500; border-radius: 4px; transition: background 0.3s ease; margin-right: 20px;"
      >发布职位</el-menu-item>
      <el-menu-item
          v-if="isApplicant"
          index="/applicant/resume"
          style="color: #fff; font-weight: 500; border-radius: 4px; transition: background 0.3s ease; margin-right: 20px;"
      >我的简历</el-menu-item>
      <el-menu-item
          v-if="isAdmin"
          index="/admin/user-management"
          style="color: #fff; font-weight: 500; border-radius: 4px; transition: background 0.3s ease; margin-right: 20px;"
      >用户管理</el-menu-item>
      <el-menu-item
      v-if="isAdmin"
          index="/admin/job-management"
          style="color: #fff; font-weight: 500; border-radius: 4px; transition: background 0.3s ease; margin-right: 20px;"
      >职位管理</el-menu-item>
      <el-menu-item
          v-if="isAdmin"
          index="/admin/company-verification"
          style="color: #fff; font-weight: 500; border-radius: 4px; transition: background 0.3s ease; margin-right: 20px;"
      >企业认证</el-menu-item>
      <el-menu-item
          v-if="isAdmin"
          index="/admin/applicant-management"
          style="color: #fff; font-weight: 500; border-radius: 4px; transition: background 0.3s ease; margin-right: 20px;"
      >求职者管理</el-menu-item>
      <el-menu-item
          v-if="isAdmin"
          index="/admin/system-settings"
          style="color: #fff; font-weight: 500; border-radius: 4px; transition: background 0.3s ease; margin-right: 20px;"
      >系统设置</el-menu-item>
      <el-menu-item
          v-if="isAdmin"
          index="/admin/data-statistics"
          style="color: #fff; font-weight: 500; border-radius: 4px; transition: background 0.3s ease; margin-right: 20px;"
      >数据统计</el-menu-item>
      <el-menu-item
          v-if="isAdmin"
          index="/admin/security-management"
          style="color: #fff; font-weight: 500; border-radius: 4px; transition: background 0.3s ease; margin-right: 20px;"
      >安全管理</el-menu-item>
    </el-menu>
    <div @click="showCityDialog = true" style="display: flex; align-items: center; cursor: pointer;">
      <el-icon style="margin-right: 5px"><Location /></el-icon>
      <span>{{ currentCity }}</span>
      <span style="margin-left: 5px">[切换]</span>
    </div>
    <div
        class="user"
        style="cursor: pointer; display: flex; align-items: center;"
    >
      <el-dropdown v-if="nickname">
        <span class="el-dropdown-link" style="color: #fff; display: flex; align-items: center; padding: 0 10px; border-radius: 4px; transition: background 0.3s ease;">
          {{ nickname }}<i class="el-icon-arrow-down el-icon--right"></i>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="navigateToProfile" style="color: #000000; font-weight: 500; border-radius: 4px; transition: background 0.3s ease;">个人信息</el-dropdown-item>
            <el-dropdown-item @click="changePassword" style="color: #000000; font-weight: 500; border-radius: 4px; transition: background 0.3s ease;">修改密码</el-dropdown-item>
            <el-dropdown-item @click="logout" style="color: #000000; font-weight: 500; border-radius: 4px; transition: background 0.3s ease;">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <div v-else>
        <el-button
            v-if="!nickname"
            link
            @click="navigateToLogin()"
            style="color: #fff; font-weight: 500; border-radius: 4px; transition: background 0.3s ease; margin-right: 20px;"
        >登录/注册</el-button>
        <span v-else style="color: #fff; font-weight: 500;">{{ nickname }}</span>
      </div>
    </div>
  </el-header>

  <!-- 城市选择对话框 -->
  <el-dialog
      v-model="showCityDialog"
      width="70%"
  >
    <el-row :gutter="20">
      <el-col :span="8">
        <span style="font-size: 20px;">按省份选择</span>
        <el-select
            v-model="selectedProvince"
            placeholder="省份"
            @change="fetchCities"
        >
          <el-option-group
              v-for="group in provinces"
              :key="group.label"
              :label="group.label"
          >
            <el-option
                v-for="option in group.options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
            ></el-option>
          </el-option-group>
        </el-select>
      </el-col>
      <el-col :span="8" v-if="selectedProvince">
        <span style="font-size: 20px;">按城市选择</span>
        <el-select
            v-model="selectedCity"
            placeholder="城市"
        >
          <el-option
              v-for="city in filteredCities"
              :key="city.value"
              :label="city.label"
              :value="city.value"
          ></el-option>
        </el-select>
      </el-col>
      <el-col :span="8">
        <span style="font-size: 20px;">直接搜索</span>
        <el-input
            v-model="searchCity"
            placeholder="输入城市名称"
            @input="filterCities"
        ></el-input>
      </el-col>
    </el-row>


    <h3>热门城市</h3>
    <el-row :gutter="20">
      <el-col :span="6" v-for="city in hotCities" :key="city">
        <el-button type="text" @click="selectCity(city)">{{ city }}</el-button>
      </el-col>
    </el-row>

    <div style="display: flex; flex-wrap: wrap; align-items: center;">
      <span style="font-size: 16px; margin-right: 10px;">按字母选择:</span>
      <a
          v-for="letter in Object.keys(citiesByLetter)"
          :key="letter"
          href="#"
          @click.prevent="scrollToLetter(letter)"
          :class="{ 'selected-letter': selectedLetter === letter }" style="margin: 15px; text-decoration: none; font-family: 宋体; font-size: 14px; color: #409eff; font-weight: bold;"
      >{{ letter }}</a>
    </div>
    <div>
      <ul style="list-style-type: none; padding-left: 0;">
        <li v-for="(cities, letter) in citiesByLetter" :key="letter" :id="`letter-${letter}`" style="margin-top: 20px;">
          <strong :class="{ 'selected-letter': selectedLetter === letter }"  style="display: inline-block; font-size: 40px;margin-right: 10px;">{{ letter }}</strong>
          <ul style="list-style-type: none; padding-left: 0; display: inline-block;">
            <li v-for="city in cities" :key="city" style="display: inline-block; margin-right: 10px;">
              <a href="#" @click.prevent="selectCity(city)" style="text-decoration: none; font-size:20px;color: black;">{{ city }}</a>
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </el-dialog>
</template>

<script setup>

  import { ref, onMounted } from 'vue';

  import { useRouter } from 'vue-router';
  import axios from "axios";
 const getUser =()=>{
    return localStorage.user?JSON.parse(localStorage.user):null;
  }
  const user = ref(getUser());
  const router = useRouter();
  const nickname = ref('');
  const isRecruiter = ref(false);
  const isApplicant = ref(false);
  const isAdmin = ref(false);
  const showCityDialog = ref(false);
  const selectedProvince = ref('');
  const selectedCity = ref('');
  const currentCity = ref('武汉'); // 新增的响应式变量
  const provinces = ref([]);
  const cities = ref([]); // 新增的响应式变量
  const allCities = ref([]); // 所有城市的列表
  const hotCities = ref(['全国','北京', '上海', '广州', '深圳', '成都', '西安']);
  const citiesByLetter = ref({
  A: ['鞍山', '安庆'],
  B: ['北京', '保定'],
  C: ['重庆', '长沙'],
  D: ['大连', '丹东'],
  E: ['鄂尔多斯', '鄂州'],
  F: ['福州', '佛山'],
  G: ['广州', '贵阳'],
  H: ['杭州', '合肥'],
  J: ['济南', '嘉兴'],
  K: ['昆明', '开封'],
  L: ['廊坊', '临沂'],
  M: ['马鞍山', '茂名'],
  N: ['南昌', '南宁'],
  P: ['盘锦', '莆田'],
  Q: ['青岛', '秦皇岛'],
  S: ['石家庄', '苏州'],
  T: ['太原', '天津'],
  W: ['武汉', '无锡'],
  X: ['西安', '厦门'],
  Y: ['烟台', '扬州'],
  Z: ['珠海', '郑州']
});
  const selectedLetter = ref(''); // 新增的响应式变量
  const searchCity = ref(''); // 直接搜索的输入框
  const filteredCities = ref([]); // 过滤后的城市列表

  const scrollToLetter = (letter) => {
  const element = document.getElementById(`letter-${letter}`);
  if (element) {
  element.scrollIntoView({ behavior: 'smooth' });
}
  selectedLetter.value = letter; // 更新选中的字母
};

  const selectCity = (city) => {
  console.log(`选择了城市: ${city}`);
  currentCity.value = city; // 更新当前显示的城市
  showCityDialog.value = false;
};

  onMounted(() => {
    console.log('用户信息',user.value);
    if(user.value !==null) {
      const role = user.value.role;
      isRecruiter.value = role === 1;
      isApplicant.value = role === 2;
      isAdmin.value = role === 0;
      nickname.value=user.value.nickname;
    }
  // 获取所有城市
  fetchAllCities();
});

  const logout = () => {
    console.log('用户id',user.value.id);
  // 退出登录逻辑
    axios.post(BASEURL + '/common/logout',{id:user.value.id})
        .then(response => {
          if (response.data.code === 2000) {
            console.log('退出登录成功');
            // 清除本地存储的用户信息
            localStorage.removeItem('user');
            // 重定向到登录页面
            router.push('/login');
          } else {
            console.log(response.data.message);
          }
        });
  };
  //修改密码
  const changePassword = () => {
  router.push('/change-password');
 };
  const navigateToLogin = (userType) => {
  if (userType) {
  router.push({ path: '/login', query: { userType } });
} else {
  router.push('/login');
}
};



  const fetchAllCities = async () => {
  try {
  const response = await fetch('/api/all-cities');
  if (!response.ok) {
  throw new Error('Network response was not ok');
}
  const data = await response.json();
  allCities.value = data.map(item => ({ value: item.name, label: item.name }));
  filteredCities.value = allCities.value; // 初始化过滤后的城市列表
} catch (error) {
  console.error(error);
}
};
  const navigateToProfile = () => {
    console.log('正在导航到个人信息页面');
    router.push('/personal-information')
  };
  const fetchCities = async (province) => {
  if (province) {
  try {
  const response = await fetch(`/api/cities?province=${province}`);
  if (!response.ok) {
  throw new Error('Network response was not ok');
}
  const data = await response.json();
  cities.value = data.map(item => ({ value: item.name, label: item.name }));
} catch (error) {
  console.error(error);
}
} else {
  cities.value = [];
}
};

  const filterCities = (query) => {
  filteredCities.value = allCities.value.filter(city => city.label.includes(query));
};
  const searchJobs = () => {
    router.push({ path: '/job-seeker/job-search' }); // 跳转到 JobSearch 页面，并传递当前城市参数
  };

</script>

<style scoped>
.selected-letter {
  color: #1890ff; /* 选中字母的文字颜色 */
}
</style>